package co.edu.udistrital.analyzer.newversion;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class SearchIndex {

	public SearchIndex() {
		// TODO Auto-generated constructor stub
	}

	public List<DocumentSearchDto> searchDocumentsFromIndex(
			String indexClassification, String keyTerms, float hitsScore) {
		List<DocumentSearchDto> listDocuments = null;
		IndexReader indexReader = null;
		IndexSearcher indexSearcher = null;

		try {
			indexReader = IndexReader.open(FSDirectory.open(new File(
					indexClassification)));
			indexSearcher = new IndexSearcher(indexReader);

			Analyzer analyzer = AnalyzerFactory.getAnalizer(Version.LUCENE_36,
					AnalyzerFactory.SPANISH, false);

			QueryParser parser = new QueryParser(Version.LUCENE_36,
					LuceneIndexer.CONTENT, analyzer);
			Query query = parser.parse(keyTerms);

			ScoreDoc[] hits = indexSearcher.search(query, null, 50).scoreDocs;

			listDocuments = new ArrayList<DocumentSearchDto>();

			for (int i = 0; i < hits.length; i++) {
				if (hits[i].score > hitsScore) {
					Document hitDoc = indexSearcher.doc(hits[i].doc);

					DocumentSearchDto document = new DocumentSearchDto();
					// document.setIdDocument(hits[i].doc);
					Fieldable documentIdField = hitDoc
							.getFieldable(LuceneIndexer.DOCUMENT_ID);
					if (documentIdField != null
							&& documentIdField.stringValue() != null) {
						document.setIdDocument(documentIdField.stringValue());
					}
					Fieldable documentNameField = hitDoc
							.getFieldable(LuceneIndexer.FILENAME);
					if (documentNameField != null
							&& documentNameField.stringValue() != null) {
						document.setNameDocument(obtenerNombreDocumento(documentNameField
								.stringValue()));
					}

					listDocuments.add(document);
				}
			}

		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			if (indexSearcher != null) {
				try {
					indexSearcher.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (indexReader != null) {
				try {
					indexReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return listDocuments;
	}

	private String obtenerNombreDocumento(String parentFile) {
		String documento;
		String separador = "";

		if (System.getProperty("os.name").equalsIgnoreCase("linux")) {
			separador = System.getProperty("file.separator");
		} else {
			separador = "\\\\";
		}

		String[] parent = parentFile.split(separador);
		documento = parent[parent.length - 1];

		return documento;
	}

	/**
	 * Searches a document from its UUID
	 * 
	 * @param indexDir
	 * @param id
	 * @return
	 */
	public Document searchById(String indexDir, String id) {
		Document hitDoc = null;
		IndexReader indexReader = null;
		IndexSearcher indexSearcher = null;
		try {
			indexReader = IndexReader
					.open(FSDirectory.open(new File(indexDir)));
			indexSearcher = new IndexSearcher(indexReader);
			Term t = new Term(LuceneIndexer.DOCUMENT_ID, id);
			Query query = new TermQuery(t);
			TopDocs hits = indexSearcher.search(query, 1);
			ScoreDoc[] docs = hits.scoreDocs;
			hitDoc = indexSearcher.doc(docs[0].doc);
			return hitDoc;
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (indexSearcher != null) {
				try {
					indexSearcher.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (indexReader != null) {
				try {
					indexReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return hitDoc;
	}

}
